package prometheuscli

import (
	"fmt"
	"log"
)

var histogramPercentileMetric string = `histogram_quantile(%f,sum(rate(kindling_span_trace_duration_nanoseconds_bucket{content_key="%s"}[%s])) by (%s))`
var requestCallsRateMetric string = `sum by (content_key) (rate(kindling_span_trace_duration_nanoseconds_count{content_key="%s"}[%s]))`
var requestCallsAvgLatency string = `sum by (content_key) (rate(kindling_span_trace_duration_nanoseconds_sum{content_key="%s"}[%s]))
/sum by (content_key) (rate(kindling_span_trace_duration_nanoseconds_count{content_key="%s"}[%s]))`

var defaultDuration = "6h"

func SetDefaultDuration(duration string) {
	defaultDuration = duration
}

func GetHistogramQuartileFromPrometheus(contentKey string, quantile int, timestamp int64) (float64, error) {
	query := fmt.Sprintf(histogramPercentileMetric, quantile, contentKey, defaultDuration, mAPI.HistogramQuantileLabel())
	return mAPI.pqlVector(query, timestamp)
}

func GetRequestCallsAvgLatency(contentKey string, start string, end string) (map[int64]any, error) {
	query := fmt.Sprintf(requestCallsAvgLatency, contentKey, "1m", contentKey, "1m")
	return mAPI.pqlRangeMatrix(query, start, end, "MINUTE")
}

// 查询平均每秒访问次数
func GetRequestCallsPerSecond(contentKey string, start string, end string) (map[int64]any, error) {
	query := fmt.Sprintf(requestCallsRateMetric, contentKey, "1m")
	return mAPI.pqlRangeMatrix(query, start, end, "MINUTE")
}

// 查询p90，P95数据
func GetResponseTimePercentile(percent float64, contentKey string, start string, end string) (map[int64]any, error) {
	query := fmt.Sprintf(histogramPercentileMetric, percent, contentKey, "1m", mAPI.HistogramQuantileLabel())

	value, err := mAPI.pqlRangeMatrix(query, start, end, "MINUTE")
	if err != nil {
		log.Printf("Error: %v\n", err)
		return nil, err
	}

	return value, nil
}
